package com.gjy.sb.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @author gjy
 * @version 1.0
 * @since 2025-01-02 18:51:45
 */
@RestControllerAdvice("com.gjy.sb")
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 忽略参数异常处理器
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String paramMissionExceptionHandler(MissingServletRequestParameterException e) {
        String message = e.getMessage();
        log.error("忽略参数异常处理器");
        return message;
    }

    /**
     * 缺少请求体异常处理器
     */
    @ExceptionHandler({HttpMessageNotReadableException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String paramBodyMissionExceptionHandler(HttpMessageNotReadableException e) {
        String message = e.getMessage();
        log.error("缺少请求体异常处理器");
        return message;
    }

    /**
     * 参数效验异常处理器
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String paramExceptionHandler(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        log.info("binding: {}", bindingResult);
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            if (!CollectionUtils.isEmpty(allErrors)) {
                FieldError fieldError = (FieldError) allErrors.get(0);
                return fieldError.getDefaultMessage();
            }
        }
        log.error("参数效验异常处理器");
        return "参数效验异常处理器";
    }

    /**
     * 自定义参数错误异常处理器
     */
    @ExceptionHandler({ParamErrorException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String paramErrorExceptionHandler(ParamErrorException e) {
        String message = e.getMessage();
        log.error("自定义参数错误异常处理器");
        return message;
    }

}
